package com.pivotal.cloud.crypto.encrypt;

import com.pivotal.cloud.crypto.codec.Hex;
import com.pivotal.cloud.crypto.keygen.BytesKeyGenerator;
import com.pivotal.cloud.crypto.keygen.KeyGenerators;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;

/**
 * @className: com.pivotal.cloud.security.crypto.encrypt.BouncyCastleAesBytesEncryptor
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-BouncyCastleAesBytesEncryptor类，主要位于Security安全模块-Aes加密模块
 * @content: BouncyCastleAesBytesEncryptor-Aes加密
 * @author: Powered by Marklin
 * @datetime: 2025-06-25 22:10
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public abstract class BouncyCastleAesBytesEncryptor implements BytesEncryptor {

	public final KeyParameter secretKey;

	public final BytesKeyGenerator ivGenerator;

	BouncyCastleAesBytesEncryptor(String password, CharSequence salt) {
		this(password, salt, KeyGenerators.secureRandom(16));
	}

	BouncyCastleAesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator) {
		if (ivGenerator.getKeyLength() != 16) {
			throw new IllegalArgumentException("ivGenerator key length != block size 16");
		}
		this.ivGenerator = ivGenerator;
		PBEParametersGenerator keyGenerator = new PKCS5S2ParametersGenerator();
		byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toCharArray());
		keyGenerator.init(pkcs12PasswordBytes, Hex.decode(salt), 1024);
		this.secretKey = (KeyParameter) keyGenerator.generateDerivedParameters(256);
	}

}
